package com.mallcai.bigdata.ladon.controller.peekdata;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mallcai.bigdata.ladon.controller.peekdata.form.ModelForm;
import com.mallcai.bigdata.ladon.controller.peekdata.form.ModelForm.*;
import com.mallcai.bigdata.ladon.dpl.entity.peekdata.Model;
import com.mallcai.bigdata.ladon.dpl.entity.peekdata.ModelMeta;
import com.mallcai.bigdata.ladon.dpl.entity.peekdata.ModelSchema;
import com.mallcai.bigdata.ladon.service.common.IDatasourceService;
import com.mallcai.bigdata.ladon.service.peekdata.IModelSchemaService;
import com.mallcai.bigdata.ladon.service.peekdata.IModelService;
import com.mallcai.bigdata.ladon.vo.ColumnVo;
import com.mallcai.bigdata.ladon.vo.MyPageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 取数模型管理
 * Created by oneape<oneape15@163.com>
 * Created 2019-05-20 15:16.
 * Modify:
 */
@RequestMapping("/peekdata/model")
@RestController
@Slf4j
public class ModelManageController {
    @Autowired
    private IModelService       iModelService;
    @Autowired
    private IDatasourceService  iDatasourceService;
    @Autowired
    private IModelSchemaService iModelSchemaService;


    @RequestMapping("/add")
    public String addModel(@RequestBody @Validated(value = AddCheck.class) ModelForm form) {
        Model model = form.toEntity();
        List<ModelMeta> fields = form.getFields();
        if (fields == null || fields.isEmpty()) {
            throw new BusinessException("表字段不能为空");
        }

        int status = iModelService.addModelInfo(model, fields);
        if (status <= 0) {
            throw new BusinessException("添加模型失败");
        }
        return "添加模型成功";
    }

    @RequestMapping("/edit")
    public String editModel(@RequestBody @Validated(value = EditCheck.class) ModelForm form) {
        Model model = form.toEntity();
        List<ModelMeta> fields = form.getFields();
        if (fields == null || fields.isEmpty()) {
            throw new BusinessException("表字段不能为空");
        }

        int status = iModelService.editModelInfo(model, fields);
        if (status <= 0) {
            throw new BusinessException("修改模型失败");
        }

        return "修改模型成功";
    }

    @RequestMapping("/upgrade")
    public String upgradeModel(@RequestBody @Validated(value = EditCheck.class) ModelForm form) {
        Model model = form.toEntity();
        List<ModelMeta> fields = form.getFields();
        if (fields == null || fields.isEmpty()) {
            throw new BusinessException("表字段不能为空");
        }

        int status = iModelService.upgradeModelInfo(model, fields);
        if (status <= 0) {
            throw new BusinessException("修改模型失败");
        }

        return "修改模型成功";
    }

    @RequestMapping("/changeStatus")
    public String changeStatus(@RequestBody @Validated(value = ChangeStatusCheck.class) ModelForm form) {
        Model model = form.toEntity();

        int status = iModelService.changeStatus(model);
        if (status <= 0) {
            throw new BusinessException("修改模型失败");
        }

        return "修改模型成功";
    }

    @RequestMapping("/del")
    public String delModel(@RequestBody @Validated(value = IdCheck.class) ModelForm form) {
        Model model = form.toEntity();
        int status = iModelService.deleteModelInfo(model);
        if (status <= 0) {
            throw new BusinessException("删除模型失败");
        }

        return "删除模型成功";
    }

    @RequestMapping("/getById")
    public Model getModelById(@RequestBody @Validated(value = IdCheck.class) ModelForm form) {
        Model model = iModelService.getById(form.getModelId());
        if (model == null) {
            throw new BusinessException("删除模型失败");
        }

        return model;
    }

    @RequestMapping("/getByPage")
    public MyPageInfo getByPage(@RequestBody @Validated ModelForm form) {
        PageHelper.startPage(form.getCurrentPage(), form.getPageSize());
        List<Model> models = iModelService.getByParams(form.getParams());
        PageInfo<Model> pageInfo = new PageInfo<>(models);

        return new MyPageInfo<>(pageInfo);
    }


    /**
     * 获取所有可用的模型列表
     *
     * @param form ModelForm
     * @return List
     */
    @RequestMapping("/getAllModels")
    public List<Model> getAllModels(@RequestBody @Validated ModelForm form) {
        return iModelService.getAllModels();
    }

    /**
     * 根据模型Id获取字段列表(隐藏的字段不返回)
     *
     * @param form ModelForm
     * @return List
     */
    @RequestMapping("/listModelMeta")
    public List<ModelMeta> listModelMeta(@RequestBody @Validated(value = IdCheck.class) ModelForm form) {
        List<ModelMeta> mms = iModelService.listMetaByModelId(form.getModelId());
        List<ModelMeta> filters = new ArrayList<>();
        if (mms != null && mms.size() > 0) {
            filters = mms.stream()
                    .filter(m -> m.getDisplay() == 1)
                    .collect(Collectors.toList());
        }

        return filters;
    }

    @RequestMapping("/getColumns")
    public List<ModelMeta> getColumns(@RequestBody @Validated(value = GetColumnCheck.class) ModelForm form) {
        List<ModelMeta> metas = new ArrayList<>();
        Long modelId = form.getModelId();
        if (modelId == null || modelId <= 0) {
            List<ColumnVo> columns = iDatasourceService.getTableColumns(form.getDatasourceId(), form.getTableName());
            if (columns != null) {
                for (ColumnVo vo : columns) {
                    ModelMeta mm = new ModelMeta();
                    mm.setDataType(vo.getType());
                    mm.setOriginalDataType(vo.getOriginalType());
                    mm.setName(vo.getName());
                    mm.setDisplay(1);
                    mm.setId(-1L);
                    mm.setShowName(vo.getName());
                    metas.add(mm);
                }
            }
        } else {
            metas = iModelService.listMetaByModelId(form.getModelId());
        }
        return metas;
    }


    @RequestMapping("/getUpgradeColumns")
    public List<ModelMeta> getUpgradeColumns(@RequestBody @Validated(value = GetUpgradeColumnCheck.class) ModelForm form) {
        List<ModelMeta> metas = new ArrayList<>();
        List<ModelMeta> existedList = iModelService.listMetaByModelId(form.getModelId());
        Set<String> existedMeta = existedList.stream().map(ModelMeta::getName).collect(Collectors.toSet());
        List<ColumnVo> columns = iDatasourceService.getTableColumns(form.getDatasourceId(), form.getTableName());
        if (columns != null) {
            for (ColumnVo vo : columns) {
                if (!existedMeta.contains(vo.getName())) {
                    ModelMeta mm = new ModelMeta();
                    mm.setDataType(vo.getType());
                    mm.setName(vo.getName());
                    mm.setDisplay(1);
                    mm.setId(-1L);
                    mm.setShowName(vo.getName());
                    metas.add(mm);
                }
            }
        }
        return metas;
    }


    @RequestMapping("/getSchemas")
    public List<ModelSchema> getSchemas(@RequestBody @Validated(value = GetColumnCheck.class) ModelForm form) {
        Map<String, Object> params = new HashMap<>();
        params.put("datasourceId", form.getDatasourceId());
        params.put("tableName", form.getTableName());
        return iModelSchemaService.getByParams(params);
    }


    @RequestMapping("/readModel")
    public Model readModel(@RequestBody @Validated(value = IdCheck.class) ModelForm form) {
        return iModelService.readModel(form.getModelId());
    }


}
